package com.example.user.service.code.impl;

import com.example.framework.common.util.EncryptUtils;
import com.example.module.system.api.mail.MailSendApi;
import com.example.module.system.api.mail.dto.EmailSendParam;
import com.example.module.system.dal.redis.RedisKeyConstants;
import com.example.user.config.EmailCodeProperties;
import com.example.user.constants.SourceTypeEnum;
import com.example.user.controller.auth.vo.UserSourceType;
import com.example.user.service.code.CodeService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

@Slf4j
@Service
@RequiredArgsConstructor
public class MailService extends CodeService {

    @Resource
    private MailSendApi mailSendApi;

    private final EmailCodeProperties emailCodeProperties;

    @Value("${encrypt.aes.secret}")
    private String aesSecret;

    @Override
    public String getRedisKey(String email) {
        return RedisKeyConstants.MAIL_KEY_PREFIX + EncryptUtils.AesEncrypt(email, aesSecret);
    }

    public void sendCode(UserSourceType reqVo) {
        String email = reqVo.getId();
        Assert.isTrue(EmailValidator.getInstance().isValid(email), "邮箱格式不合法");
        String identifyingCode = super.checkFrequencyAndGenerateCode(emailCodeProperties.getCodeFrequency(), emailCodeProperties.getLength(), email, emailCodeProperties.getExpireSeconds());
        EmailSendParam emailSendParam = new EmailSendParam()
                .setReceiver(email)
                .setTitle(emailCodeProperties.getTitle())
                .setMsg(String.format(emailCodeProperties.getTemplate(), identifyingCode));
        log.info("准备发送邮件验证码，emailSendParam={}", emailSendParam);
        mailSendApi.sendSingleMsg(emailSendParam);
        super.setCache(emailCodeProperties.getCodeFrequency(), email, identifyingCode, emailCodeProperties.getExpireSeconds());
    }

    @Override
    public SourceTypeEnum getType() {
        return SourceTypeEnum.EMAIL;
    }
}
